package com.jiepos.mpos.biz.affix.service;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppAffixInfDao;
import com.jiepos.mpos.common.dao.AppCustomBankcardDao;
import com.jiepos.mpos.common.entity.App_Affix_InfEntity;
import com.jiepos.mpos.common.entity.App_Custom_BankcardEntity;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.FileUtils;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 附件业务类 要求能简洁地表达出类的功能和职责
 * 
 * @ProjectName: [mpos1]
 * @Package com.jiepos.mpos.biz.affix.service
 * @author 肖志伟
 * @version 1.0
 * @since 2017年9月22日 下午5:35:43
 * @history（历次修订内容、修订人、修订时间等） @UpdateRemark [说明本次修改内容]
 * @Copyright (c) 2017 江苏杰博实信息技术有限公司
 */
@Service
public class AppAffixInfService extends BaseService {

	@Autowired
	private AppAffixInfDao appAffixInfDao;

	@Autowired
	private AppCustomBankcardDao appCustomBankcardDao;
	/**
	 * 获取会员认证的图片附件信息
	 * 
	 * @param custom_uuid
	 * @return
	 */
	public List<Map<String, Object>> getCustomCertificatePic(String custom_uuid) {
		StringBuffer sb = new StringBuffer();
		sb.append("select t1.* from "+Table.T_APP_AFFIX_INF +" t1 ");
		sb.append("where (t1.affix_tp = '" + SystemConstant.AFFIX_TP_02
				+ "' or t1.affix_tp = '"+SystemConstant.AFFIX_TP_01+"') and t1.affix_idx = ? and t1.rec_st != ?");
		sb.append("order by t1.store_tp asc");
		List list = new ArrayList();
		list.add(custom_uuid);
		list.add(SystemConstant.REC_ST_0);
		List<Map<String, Object>> map = appAffixInfDao.queryForList(sb.toString(), list);
		return map;
	}
	
	/**
	 * 获取待审核的银行卡图片信息
	 * @param custom_uuid
	 * @return
	 */
	public List<Map<String, Object>> getCustomCertificateNewPic(String custom_uuid) {
		StringBuffer sb = new StringBuffer();
		sb.append("select t1.* from "+Table.T_APP_AFFIX_INF +" t1 ");
		sb.append("where t1.affix_tp = '" + SystemConstant.AFFIX_TP_03+"' and t1.rec_st != ? and t1.affix_idx = ? ");
		sb.append(" order by t1.store_tp asc");
		List list = new ArrayList();
		list.add(SystemConstant.REC_ST_0);
		list.add(custom_uuid);
		List<Map<String, Object>> map = appAffixInfDao.queryForList(sb.toString(), list);
		return map;
	}
	
	/**
	 * 获取原银行卡图片信息
	 * @param custom_uuid
	 * @param bankcard_uuid
	 * @return
	 */
	public List<Map<String, Object>> getOldPic(String custom_uuid,String bankcard_uuid){
		StringBuffer sb = new StringBuffer();
		List list = new ArrayList();
		sb.append("select t1.* from "+Table.T_APP_AFFIX_INF +" t1 ")
			.append("where ((t1.affix_tp = '" + SystemConstant.AFFIX_TP_02+"' and t1.child_affix_idx = ?) or t1.affix_tp = '"+SystemConstant.AFFIX_TP_01+"')")
			.append(" and t1.rec_st != ? and t1.affix_idx = ? ")
			.append(" order by t1.store_tp asc");
		list.add(bankcard_uuid);
		list.add(SystemConstant.REC_ST_0);
		list.add(custom_uuid);
		List<Map<String, Object>> map = appAffixInfDao.queryForList(sb.toString(), list);
		return map;
	}
	
	/**
	 * 获取新变更的银行卡图片信息
	 * @param custom_uuid
	 * @param bankcard_uuid
	 * @return
	 */
	public List<Map<String, Object>> getNewPic(String custom_uuid,String bankcard_uuid){
		StringBuffer sb = new StringBuffer();
		List list = new ArrayList();
		sb.append("select t1.* from "+Table.T_APP_AFFIX_INF +" t1 ")
			.append("where t1.affix_tp = '" + SystemConstant.AFFIX_TP_03+"' and t1.child_affix_idx = ?")
			.append(" and t1.rec_st != ? and t1.affix_idx = ? ")
			.append(" order by t1.store_tp asc");
		list.add(bankcard_uuid);
		list.add(SystemConstant.REC_ST_0);
		list.add(custom_uuid);
		List<Map<String, Object>> map = appAffixInfDao.queryForList(sb.toString(), list);
		return map;
	}
	
	/**
	 * 获图片附件信息
	 * 
	 * @param custom_uuid
	 * @return
	 */
	public List<Map<String, Object>> getAffixPic(String affix_tp,String system_uuid) {
		StringBuffer sb = new StringBuffer();
		sb.append("select t1.* from "+Table.T_APP_AFFIX_INF +" t1 ");
		sb.append("where (t1.affix_tp = ?) and t1.affix_idx = ? and  t1.rec_st="+SystemConstant.REC_ST_1 );
		sb.append(" order by t1.store_tp asc");
		List list = new ArrayList();
		list.add(affix_tp);
		list.add(system_uuid);
		List<Map<String, Object>> map = appAffixInfDao.queryForList(sb.toString(), list);
		return map;
	}
	
	/**
	 * 新增或者修改附件信息
	 * @param entity
	 * @return
	 */
	public void saveAffixPic(HttpServletRequest request, String affix_idx, Map<String, Object> map){
		String[] imgs = request.getParameterValues(SystemConstant.IMG_UPLOAD);
		if(imgs == null || imgs.length == 0){
			return;
		}
		for(String img : imgs){
			String[] _imgs = img.split("#");
			if(_imgs == null || _imgs.length != 3){
				continue;
			}
			App_Affix_InfEntity entity = appAffixInfDao.findByParamses(new String[]{"affix_tp", "store_tp", "affix_idx"}, new String[]{_imgs[0], _imgs[1], affix_idx});
			if(entity == null){
				entity = new App_Affix_InfEntity();
				entity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
				entity.setAffix_uuid(IDFactoryUtil.getUUID());// 设置主键
				entity.setAffix_idx(affix_idx);
				entity.setAffix_tp(_imgs[0]);
				entity.setStore_tp(_imgs[1]);
				entity.setAffix_path(_imgs[2]);
				entity.setLast_oper_in(SystemConstant.OPER_ADD);
				entity.setRec_crt_ts(new Timestamp(System.currentTimeMillis()));
				entity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
				appAffixInfDao.save(entity);
			}else{
				entity.setAffix_path(_imgs[2]);
				entity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
				entity.setLast_oper_in(SystemConstant.OPER_UPDATE);
				entity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
				List noChange = new ArrayList();
				noChange.add("affix_uuid");
				noChange.add("affix_idx");
				noChange.add("affix_tp");
				noChange.add("store_tp");
				appAffixInfDao.update(entity, noChange);
			}
		}
	}

	/**
	 * 根据附件索引以及大小类加载实体
	 * @param affix_idx
	 * @param affix_tp
	 * @param store_tp
	 * @return
	 */
	public App_Affix_InfEntity getAffixInfByParam(String affix_idx,String affix_tp,String store_tp){
		Object[] param1 = new Object[]{"affix_idx","affix_tp","store_tp"};
		Object[] param2 = new Object[]{affix_idx,affix_tp,store_tp};
		return appAffixInfDao.findByParamses(param1,param2);
	}

	/**
	 * 根据会员uuid得到会员图片上传路径
	 * @param custom_uuid
	 * @return
	 */
	public String getUploadFilePath(String custom_uuid){
		App_Affix_InfEntity entity = appAffixInfDao.findByParam("affix_idx", custom_uuid);
		if(entity != null){
			String path = entity.getAffix_path();
			if(path != null && path.lastIndexOf("/") != -1){
				return path.substring(0, path.lastIndexOf("/"));
			}
		}
		return null;
	}

	/**
	 * 新增或者修改附件信息 For App
	 * @param entity
	 * @return
	 */
	public String saveAffixPicForApp(App_Affix_InfEntity entity, Map<String, Object> map){
		//以是否有uuid来区分操作
		if (!StringUtils.isBlank(entity.getAffix_uuid())) {
			//更新
			entity = (App_Affix_InfEntity) this.saveCommonData(entity,map,"update");
			List noChangeList = new ArrayList();
			noChangeList.add("affix_uuid");
			noChangeList.add("rec_crt_ts");
			appAffixInfDao.update(entity,noChangeList);
		}else{
			//新增
			entity = (App_Affix_InfEntity) this.saveCommonData(entity, map, null);
			entity.setAffix_uuid(IDFactoryUtil.getUUID());
			appAffixInfDao.save(entity);
		}
		return entity.getAffix_uuid();
	}
	
	/**
	 * 用于新增附件时，更新附件索引字段
	 * @param affix_uuid 附件唯一标识
	 * @param affix_idx
	 * @param map
	 */
	public void saveAffixPic(String affix_uuid, String affix_idx, Map<String, Object> map){
		if(StringUtils.isBlank(affix_uuid) || StringUtils.isBlank(affix_idx)){
			return;
		}
		App_Affix_InfEntity entity = appAffixInfDao.findByParam("affix_uuid", affix_uuid);
		if(entity == null){
			return;
		}
		entity.setAffix_idx(affix_idx);
		entity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
		entity.setLast_oper_in(SystemConstant.OPER_UPDATE);
		entity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
		List noChange = new ArrayList();
		noChange.add("affix_uuid");
		appAffixInfDao.update(entity, noChange);
	}
	
	/**
	 * 审核通过后更新图片信息
	 * @param custom_uuid
	 * @param bankcard_uuid
	 */
	public void updateAffixPicPass(String custom_uuid,String bankcard_uuid){
		StringBuffer sb = new StringBuffer();
		List list = new ArrayList<>();
		String changeBankcardId = "";
		App_Custom_BankcardEntity app_Custom_BankcardEntity = appCustomBankcardDao.findByParam("bankcard_uuid", bankcard_uuid);
		if(app_Custom_BankcardEntity != null){
			changeBankcardId = app_Custom_BankcardEntity.getChange_bankcard_uuid() != null ? app_Custom_BankcardEntity.getChange_bankcard_uuid() : "";
		}
		
		//更改原结算卡图片
		sb.append(" update ").append(Table.T_APP_AFFIX_INF).append(" set affix_tp = ?,rec_st = ?,child_affix_idx = ?")
			.append(" where affix_idx = ? and affix_tp = ? and rec_st = ?");
		list.add(SystemConstant.AFFIX_TP_02);
		list.add(SystemConstant.REC_ST_0);
		list.add(changeBankcardId);
		list.add(custom_uuid);
		list.add(SystemConstant.AFFIX_TP_02);
		list.add(SystemConstant.REC_ST_1);
		appAffixInfDao.update(sb.toString(),list);
		//更改现结算卡图片
		list.clear();
		list.add(SystemConstant.AFFIX_TP_02);
		list.add(SystemConstant.REC_ST_1);
		list.add(bankcard_uuid);
		list.add(custom_uuid);
		list.add(SystemConstant.AFFIX_TP_03);
		list.add(SystemConstant.REC_ST_1);
		appAffixInfDao.update(sb.toString(),list);
	}
	
	/**
	 * 退回修改更新图片信息
	 * @param custom_uuid
	 * @param bankcard_uuid
	 */
	public void updateAffixPicBack(String custom_uuid,String bankcard_uuid){
		StringBuffer sb = new StringBuffer();
		List list = new ArrayList<>();
		String changeBankcardId = "";
		App_Custom_BankcardEntity app_Custom_BankcardEntity = appCustomBankcardDao.findByParam("bankcard_uuid", bankcard_uuid);
		if(app_Custom_BankcardEntity != null){
			changeBankcardId = app_Custom_BankcardEntity.getChange_bankcard_uuid() != null ? app_Custom_BankcardEntity.getChange_bankcard_uuid() : "";
		}
		
		//更改原结算卡图片
		sb.append(" update ").append(Table.T_APP_AFFIX_INF).append(" set affix_tp = ?,rec_st = ?,child_affix_idx = ?")
			.append(" where affix_idx = ? and affix_tp = ? and rec_st = ?");
		list.add(SystemConstant.AFFIX_TP_02);
		list.add(SystemConstant.REC_ST_1);
		list.add(changeBankcardId);
		list.add(custom_uuid);
		list.add(SystemConstant.AFFIX_TP_02);
		list.add(SystemConstant.REC_ST_1);
		appAffixInfDao.update(sb.toString(),list);
		//更改现结算卡图片
		list.clear();
		list.add(SystemConstant.AFFIX_TP_03);
		list.add(SystemConstant.REC_ST_1);
		list.add(bankcard_uuid);
		list.add(custom_uuid);
		list.add(SystemConstant.AFFIX_TP_03);
		list.add(SystemConstant.REC_ST_1);
		appAffixInfDao.update(sb.toString(),list);
	}

	/**
	 * 上传安卓apk文件
	 * @param request
	 * @param file
	 * @param ins_cd 机构号
	 * @param version 版本号
	 * @param loginUser
	 * @return
	 */
	public boolean uploadApkFile(HttpServletRequest request, MultipartFile file,String ins_app_history_uuid,String ins_app_uuid, String ins_cd, String version, Map loginUser){
        /*根据业务类型生成图片保存的路径*/
		StringBuffer filePath = new StringBuffer("/")
				.append(SystemConstant.FILE_UPLOAD_PATH).append("/")
				.append("appPackage").append("/")
				.append("android").append("/")
				.append(ins_cd).append("/");
		// 上传路径
		String uploadPath = request.getServletContext().getRealPath("/") + filePath.toString();
        /*重命名 保存文件*/
		String uploadName = "JQianBao" + "_" + ins_cd+"_"+version+".apk";
		File _file = FileUtils.uploadFile(file, uploadPath, uploadName);
		if(_file != null){
            // 加载库里原有数据
			App_Affix_InfEntity entity = getAffixInfByParam(ins_app_history_uuid,SystemConstant.AFFIX_TP_05,SystemConstant.STORE_TP_05_01);
			if(entity == null){
				entity = new App_Affix_InfEntity();
			}
			//设置相关信息
			entity.setAffix_path(filePath + uploadName);
			entity.setAffix_idx(ins_app_history_uuid); //附件索引UUID(变动历史uuid，方便根据历史纪录找到对应版本的apk)
			entity.setAffix_tp(SystemConstant.AFFIX_TP_05); //安装包
			entity.setStore_tp(SystemConstant.STORE_TP_05_01); //安卓apk
			entity.setChild_affix_idx(ins_app_uuid); //保存机构app uuid
			String uuid = this.saveAffixPicForApp(entity, loginUser);
			return true;
		}
		return false;
	}

	/**
	 * 获取apk地址
	 * @param historyUuid
	 * @return
	 */
	public String getNewAppUrl(String historyUuid) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT T.Affix_Path ")
				.append("  FROM ").append(Table.T_APP_AFFIX_INF)
				.append(" T  where t.Affix_Idx = ? and t.Affix_Tp = "+SystemConstant.AFFIX_TP_05+" and t.Store_Tp = "+SystemConstant.STORE_TP_05_01+" and  t.rec_st = "+SystemConstant.REC_ST_1+ " order by rec_id desc");
		List list = new ArrayList();
		list.add(historyUuid);
		List<Map> resultList = appAffixInfDao.queryForList(sql.toString(), list);
		if(CollectionUtil.isEmpty(resultList)){
			return null;
		}
		return String.valueOf(resultList.get(0).get("Affix_Path"));
	}
}
